import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Progress } from './ui/progress';
import { Badge } from './ui/badge';
import { motion, AnimatePresence } from 'motion/react';
import { Boxes, RotateCw, Box, Play, SkipForward, CheckCircle } from 'lucide-react';
import { TestResult } from '../types';

interface SpatialProblem {
  id: number;
  type: 'rotation' | 'folding' | 'perspective' | 'mental_rotation' | 'cross_section';
  question: string;
  difficulty: number;
  correctAnswer: number;
  instruction: string;
}

interface Props {
  onComplete: (result: TestResult) => void;
}

// 空间推理问题集
const SPATIAL_PROBLEMS: SpatialProblem[] = [
  {
    id: 1,
    type: 'rotation',
    question: '将左侧的L形图形顺时针旋转90度，会得到哪个结果？',
    instruction: '观察L形的方向变化',
    difficulty: 1,
    correctAnswer: 1
  },
  {
    id: 2,
    type: 'mental_rotation',
    question: '下面哪个3D立体图形与左侧图形是同一个物体？',
    instruction: '想象图形在空间中的旋转',
    difficulty: 2,
    correctAnswer: 2
  },
  {
    id: 3,
    type: 'folding',
    question: '将这个展开的正方体折叠起来，相对的面分别是什么？',
    instruction: '想象折叠过程中面的相对位置',
    difficulty: 3,
    correctAnswer: 0
  },
  {
    id: 4,
    type: 'perspective',
    question: '从正上方俯视这个立体图形，会看到什么形状？',
    instruction: '想象从不同角度观察物体',
    difficulty: 2,
    correctAnswer: 3
  },
  {
    id: 5,
    type: 'cross_section',
    question: '用平面切割这个立体图形，横截面是什么形状？',
    instruction: '想象切割后的截面形状',
    difficulty: 4,
    correctAnswer: 1
  },
  {
    id: 6,
    type: 'rotation',
    question: '将这个复杂图形绕轴旋转180度，结果是？',
    instruction: '注意图形的对称性和旋转变化',
    difficulty: 3,
    correctAnswer: 2
  },
  {
    id: 7,
    type: 'mental_rotation',
    question: '这两个3D图形是否为同一物体的不同视角？',
    instruction: '在脑中旋转图形进行比较',
    difficulty: 4,
    correctAnswer: 0
  },
  {
    id: 8,
    type: 'folding',
    question: '复杂展开图折叠后，哪些边会重合？',
    instruction: '追踪折叠过程中边的移动',
    difficulty: 5,
    correctAnswer: 1
  },
  {
    id: 9,
    type: 'perspective',
    question: '从45度角观察这个组合体，轮廓线是？',
    instruction: '考虑多个角度的视觉效果',
    difficulty: 4,
    correctAnswer: 3
  },
  {
    id: 10,
    type: 'cross_section',
    question: '复杂立体的斜切面形状是？',
    instruction: '想象斜切面与物体的交线',
    difficulty: 5,
    correctAnswer: 0
  }
];

export function SpatialReasoningTest({ onComplete }: Props) {
  const [started, setStarted] = useState(false);
  const [currentProblem, setCurrentProblem] = useState(0);
  const [answers, setAnswers] = useState<number[]>([]);
  const [timeLeft, setTimeLeft] = useState(600); // 10 minutes
  const [selectedAnswer, setSelectedAnswer] = useState<number | null>(null);
  const [showFeedback, setShowFeedback] = useState(false);
  const [testCompleted, setTestCompleted] = useState(false);
  const [finalResult, setFinalResult] = useState<TestResult | null>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const optionCanvasRefs = useRef<(HTMLCanvasElement | null)[]>([]);

  useEffect(() => {
    if (started && timeLeft > 0 && currentProblem < SPATIAL_PROBLEMS.length) {
      const timer = setTimeout(() => setTimeLeft(timeLeft - 1), 1000);
      return () => clearTimeout(timer);
    }
    
    if (timeLeft === 0 || currentProblem >= SPATIAL_PROBLEMS.length) {
      handleTestComplete();
    }
  }, [started, timeLeft, currentProblem]);

  // 绘制3D图形的函数
  const draw3DShape = useCallback((canvas: HTMLCanvasElement, shapeType: string, options: any = {}) => {
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    const { width, height } = canvas;
    const centerX = width / 2;
    const centerY = height / 2;
    const scale = options.scale || 1;
    const rotation = options.rotation || 0;
    const isCorrect = options.isCorrect || false;

    ctx.clearRect(0, 0, width, height);
    ctx.save();
    ctx.translate(centerX, centerY);
    ctx.rotate(rotation);
    ctx.scale(scale, scale);

    // 设置样式
    ctx.lineWidth = 2;
    ctx.strokeStyle = isCorrect ? '#22c55e' : '#64748b';
    ctx.fillStyle = isCorrect ? '#dcfce7' : '#f1f5f9';

    switch (shapeType) {
      case 'l_shape':
        drawLShape(ctx);
        break;
      case 'l_shape_90':
        ctx.rotate(Math.PI / 2);
        drawLShape(ctx);
        break;
      case 'l_shape_180':
        ctx.rotate(Math.PI);
        drawLShape(ctx);
        break;
      case 'l_shape_270':
        ctx.rotate(3 * Math.PI / 2);
        drawLShape(ctx);
        break;
      case 'cube_3d':
        drawCube3D(ctx, options.angle || 0);
        break;
      case 'cube_rotated':
        drawCube3D(ctx, options.angle || Math.PI / 4);
        break;
      case 'cube_net':
        drawCubeNet(ctx);
        break;
      case 'pyramid':
        drawPyramid(ctx, options.angle || 0);
        break;
      case 'cylinder':
        drawCylinder(ctx);
        break;
      case 'complex_shape':
        drawComplexShape(ctx, options.variant || 0);
        break;
      case 'cross_section_circle':
        drawCircle(ctx, 30);
        break;
      case 'cross_section_square':
        drawSquare(ctx, 30);
        break;
      case 'cross_section_triangle':
        drawTriangle(ctx, 30);
        break;
      case 'top_view_square':
        drawSquare(ctx, 40);
        break;
      case 'top_view_circle':
        drawCircle(ctx, 40);
        break;
      default:
        drawCube3D(ctx, 0);
    }

    ctx.restore();
  }, []);

  const drawLShape = (ctx: CanvasRenderingContext2D) => {
    ctx.beginPath();
    ctx.rect(-40, -40, 30, 80);
    ctx.rect(-40, -40, 80, 30);
    ctx.fill();
    ctx.stroke();
  };

  const drawCube3D = (ctx: CanvasRenderingContext2D, angle: number) => {
    const size = 40;
    const depth = 25;
    
    // 前面
    ctx.fillRect(-size/2, -size/2, size, size);
    ctx.strokeRect(-size/2, -size/2, size, size);
    
    // 右侧面
    ctx.beginPath();
    ctx.moveTo(size/2, -size/2);
    ctx.lineTo(size/2 + depth * Math.cos(angle), -size/2 - depth * Math.sin(angle));
    ctx.lineTo(size/2 + depth * Math.cos(angle), size/2 - depth * Math.sin(angle));
    ctx.lineTo(size/2, size/2);
    ctx.closePath();
    ctx.fillStyle = '#e2e8f0';
    ctx.fill();
    ctx.stroke();
    
    // 顶面
    ctx.beginPath();
    ctx.moveTo(-size/2, -size/2);
    ctx.lineTo(-size/2 + depth * Math.cos(angle), -size/2 - depth * Math.sin(angle));
    ctx.lineTo(size/2 + depth * Math.cos(angle), -size/2 - depth * Math.sin(angle));
    ctx.lineTo(size/2, -size/2);
    ctx.closePath();
    ctx.fillStyle = '#cbd5e1';
    ctx.fill();
    ctx.stroke();
  };

  const drawCubeNet = (ctx: CanvasRenderingContext2D) => {
    const size = 25;
    const positions = [
      {x: -size, y: -size}, {x: 0, y: -size}, {x: size, y: -size}, {x: 2*size, y: -size},
      {x: 0, y: 0}, {x: 0, y: size}
    ];
    
    positions.forEach((pos, index) => {
      ctx.fillRect(pos.x - size/2, pos.y - size/2, size, size);
      ctx.strokeRect(pos.x - size/2, pos.y - size/2, size, size);
      // 添加标记
      ctx.fillStyle = '#64748b';
      ctx.font = '12px sans-serif';
      ctx.textAlign = 'center';
      ctx.fillText((index + 1).toString(), pos.x, pos.y + 4);
      ctx.fillStyle = '#f1f5f9';
    });
  };

  const drawPyramid = (ctx: CanvasRenderingContext2D, angle: number) => {
    const base = 50;
    const height = 40;
    
    // 底面
    ctx.beginPath();
    ctx.moveTo(-base/2, base/2);
    ctx.lineTo(base/2, base/2);
    ctx.lineTo(base/2 + 20, base/2 - 15);
    ctx.lineTo(-base/2 + 20, base/2 - 15);
    ctx.closePath();
    ctx.fillStyle = '#e2e8f0';
    ctx.fill();
    ctx.stroke();
    
    // 前面
    ctx.beginPath();
    ctx.moveTo(-base/2, base/2);
    ctx.lineTo(base/2, base/2);
    ctx.lineTo(0, -height/2);
    ctx.closePath();
    ctx.fillStyle = '#f1f5f9';
    ctx.fill();
    ctx.stroke();
    
    // 右侧面
    ctx.beginPath();
    ctx.moveTo(base/2, base/2);
    ctx.lineTo(base/2 + 20, base/2 - 15);
    ctx.lineTo(0 + 10, -height/2 - 8);
    ctx.lineTo(0, -height/2);
    ctx.closePath();
    ctx.fillStyle = '#cbd5e1';
    ctx.fill();
    ctx.stroke();
  };

  const drawCylinder = (ctx: CanvasRenderingContext2D) => {
    const radius = 30;
    const height = 50;
    
    // 主体
    ctx.fillRect(-radius, -height/2, radius * 2, height);
    ctx.strokeRect(-radius, -height/2, radius * 2, height);
    
    // 顶部椭圆
    ctx.beginPath();
    ctx.ellipse(0, -height/2, radius, 10, 0, 0, 2 * Math.PI);
    ctx.fillStyle = '#e2e8f0';
    ctx.fill();
    ctx.stroke();
    
    // 底部椭圆
    ctx.beginPath();
    ctx.ellipse(0, height/2, radius, 10, 0, 0, 2 * Math.PI);
    ctx.fillStyle = '#cbd5e1';
    ctx.fill();
    ctx.stroke();
  };

  const drawComplexShape = (ctx: CanvasRenderingContext2D, variant: number) => {
    switch (variant) {
      case 0:
        // T形
        ctx.fillRect(-40, -15, 80, 30);
        ctx.fillRect(-15, -15, 30, 60);
        ctx.strokeRect(-40, -15, 80, 30);
        ctx.strokeRect(-15, -15, 30, 60);
        break;
      case 1:
        // 十字形
        ctx.fillRect(-40, -10, 80, 20);
        ctx.fillRect(-10, -40, 20, 80);
        ctx.strokeRect(-40, -10, 80, 20);
        ctx.strokeRect(-10, -40, 20, 80);
        break;
      case 2:
        // 阶梯形
        ctx.fillRect(-40, 0, 30, 30);
        ctx.fillRect(-10, -20, 30, 30);
        ctx.fillRect(20, -40, 30, 30);
        ctx.strokeRect(-40, 0, 30, 30);
        ctx.strokeRect(-10, -20, 30, 30);
        ctx.strokeRect(20, -40, 30, 30);
        break;
    }
  };

  const drawCircle = (ctx: CanvasRenderingContext2D, radius: number) => {
    ctx.beginPath();
    ctx.arc(0, 0, radius, 0, 2 * Math.PI);
    ctx.fill();
    ctx.stroke();
  };

  const drawSquare = (ctx: CanvasRenderingContext2D, size: number) => {
    ctx.fillRect(-size/2, -size/2, size, size);
    ctx.strokeRect(-size/2, -size/2, size, size);
  };

  const drawTriangle = (ctx: CanvasRenderingContext2D, size: number) => {
    ctx.beginPath();
    ctx.moveTo(0, -size/2);
    ctx.lineTo(-size/2, size/2);
    ctx.lineTo(size/2, size/2);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
  };

  // 生成选项图形
  const generateOptions = (problem: SpatialProblem) => {
    switch (problem.type) {
      case 'rotation':
        if (problem.id === 1) {
          return ['l_shape', 'l_shape_90', 'l_shape_180', 'l_shape_270'];
        } else {
          return ['complex_shape', 'complex_shape', 'complex_shape', 'complex_shape'].map((shape, index) => 
            ({ type: shape, variant: index, rotation: index * Math.PI / 2 })
          );
        }
      case 'mental_rotation':
        return [
          { type: 'cube_3d', angle: 0 },
          { type: 'cube_3d', angle: Math.PI / 6 },
          { type: 'cube_3d', angle: Math.PI / 4 },
          { type: 'cube_3d', angle: Math.PI / 3 }
        ];
      case 'folding':
        return ['cube_net', 'pyramid', 'cylinder', 'complex_shape'];
      case 'perspective':
        return ['top_view_square', 'top_view_circle', 'cross_section_triangle', 'top_view_square'];
      case 'cross_section':
        return ['cross_section_circle', 'cross_section_square', 'cross_section_triangle', 'complex_shape'];
      default:
        return ['cube_3d', 'pyramid', 'cylinder', 'complex_shape'];
    }
  };

  // 绘制主图形
  const drawMainShape = useCallback(() => {
    if (!canvasRef.current) return;
    
    const problem = SPATIAL_PROBLEMS[currentProblem];
    let shapeConfig: any = {};
    
    switch (problem.type) {
      case 'rotation':
        shapeConfig = { type: 'l_shape', scale: 1.2 };
        break;
      case 'mental_rotation':
        shapeConfig = { type: 'cube_3d', angle: Math.PI / 6, scale: 1.5 };
        break;
      case 'folding':
        shapeConfig = { type: 'cube_net', scale: 0.8 };
        break;
      case 'perspective':
        shapeConfig = { type: 'cube_3d', angle: Math.PI / 4, scale: 1.2 };
        break;
      case 'cross_section':
        shapeConfig = { type: 'cylinder', scale: 1.2 };
        break;
    }
    
    draw3DShape(canvasRef.current, shapeConfig.type, shapeConfig);
  }, [currentProblem, draw3DShape]);

  // 绘制选项图形
  const drawOptions = useCallback(() => {
    if (currentProblem >= SPATIAL_PROBLEMS.length) return;
    
    const problem = SPATIAL_PROBLEMS[currentProblem];
    const options = generateOptions(problem);
    
    options.forEach((option, index) => {
      const canvas = optionCanvasRefs.current[index];
      if (!canvas) return;
      
      const isCorrect = showFeedback && index === problem.correctAnswer;
      
      if (typeof option === 'string') {
        draw3DShape(canvas, option, { isCorrect });
      } else {
        draw3DShape(canvas, option.type, { ...option, isCorrect });
      }
    });
  }, [currentProblem, showFeedback, draw3DShape]);

  useEffect(() => {
    if (started && currentProblem < SPATIAL_PROBLEMS.length) {
      drawMainShape();
      drawOptions();
    }
  }, [currentProblem, started, showFeedback, drawMainShape, drawOptions]);

  const handleAnswer = (answerIndex: number) => {
    setSelectedAnswer(answerIndex);
    setShowFeedback(true);
    
    setTimeout(() => {
      const newAnswers = [...answers, answerIndex];
      setAnswers(newAnswers);
      setCurrentProblem(currentProblem + 1);
      setSelectedAnswer(null);
      setShowFeedback(false);
    }, 2000);
  };

  const handleTestComplete = () => {
    const correctAnswers = answers.reduce((count, answer, index) => {
      return count + (answer === SPATIAL_PROBLEMS[index]?.correctAnswer ? 1 : 0);
    }, 0);
    
    const score = Math.round((correctAnswers / SPATIAL_PROBLEMS.length) * 100);
    const accuracy = answers.length > 0 ? (correctAnswers / answers.length) * 100 : 0;
    
    let level = '';
    if (score >= 90) level = '空间大师';
    else if (score >= 80) level = '空间达人';
    else if (score >= 70) level = '空间能手';
    else if (score >= 60) level = '空间新手';
    else level = '需要训练';

    const result: TestResult = {
      id: Date.now().toString(),
      testType: '空间推理测试',
      score,
      details: `准确率 ${accuracy.toFixed(1)}%, 完成 ${answers.length}/${SPATIAL_PROBLEMS.length} 题, 等级: ${level}`,
      timestamp: new Date()
    };

    setFinalResult(result);
    setTestCompleted(true);
  };

  const handleSaveResult = () => {
    if (finalResult) {
      onComplete(finalResult);
    }
  };

  const skipProblem = () => {
    const newAnswers = [...answers, -1]; // -1 表示跳过
    setAnswers(newAnswers);
    setCurrentProblem(currentProblem + 1);
  };

  const formatTime = (seconds: number) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
  };

  if (!started) {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-orange-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-orange-600 to-amber-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <Boxes className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">空间推理测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您的3D空间想象能力和立体几何推理</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-orange-50 to-amber-50 rounded-xl p-6 border border-orange-100">
              <h3 className="font-semibold text-orange-900 mb-4 flex items-center gap-2">
                <Box className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>观察左侧的3D图形和操作描述</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p>在脑中进行旋转、折叠或透视变换</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>从4个选项中选择正确的结果</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>每题有充足时间思考，可跳过困难题目</p>
                </div>
              </div>
            </div>

            <div className="grid md:grid-cols-2 gap-4">
              <div className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-4 border border-blue-200">
                <h4 className="font-semibold text-blue-800 mb-2 flex items-center gap-2">
                  <RotateCw className="w-4 h-4" />
                  图形旋转
                </h4>
                <p className="text-sm text-blue-700">在3D空间中旋转图形</p>
              </div>
              <div className="bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl p-4 border border-purple-200">
                <h4 className="font-semibold text-purple-800 mb-2 flex items-center gap-2">
                  <Box className="w-4 h-4" />
                  立体折叠
                </h4>
                <p className="text-sm text-purple-700">想象展开图的折叠过程</p>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl border border-orange-200">
                <div className="text-2xl font-bold text-orange-600 mb-1">5</div>
                <div className="text-sm text-orange-700">任务类型</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-amber-50 to-amber-100 rounded-xl border border-amber-200">
                <div className="text-2xl font-bold text-amber-600 mb-1">10</div>
                <div className="text-sm text-amber-700">推理题目</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-orange-50 to-amber-50 rounded-xl border border-orange-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">10分钟</div>
                <div className="text-sm text-slate-700">测试时间</div>
              </div>
            </div>

            <Button 
              onClick={() => setStarted(true)}
              className="w-full bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0 min-w-[140px] h-12"
              size="lg"
            >
              开始测试
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (testCompleted && finalResult) {
    const correctAnswers = answers.reduce((count, answer, index) => {
      return count + (answer === SPATIAL_PROBLEMS[index]?.correctAnswer ? 1 : 0);
    }, 0);
    
    const getRating = () => {
      if (finalResult.score >= 90) return { text: '空间大师', color: 'text-yellow-500' };
      if (finalResult.score >= 80) return { text: '空间达人', color: 'text-green-500' };
      if (finalResult.score >= 70) return { text: '空间能手', color: 'text-blue-500' };
      if (finalResult.score >= 60) return { text: '空间新手', color: 'text-gray-500' };
      return { text: '需要训练', color: 'text-orange-500' };
    };

    const rating = getRating();
    
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto space-y-6"
      >
        <Card>
          <CardHeader className="text-center">
            <CardTitle className="flex items-center justify-center gap-2">
              <CheckCircle className="w-6 h-6 text-orange-500" />
              测试完成！
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="text-center space-y-4">
              <div className="text-6xl font-bold text-primary">
                {finalResult.score}
              </div>
              <div className={`text-xl font-semibold ${rating.color}`}>
                {rating.text}
              </div>
            </div>

            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center p-4 bg-green-50 dark:bg-green-950 rounded-lg">
                <div className="text-2xl font-bold text-green-600">{correctAnswers}</div>
                <div className="text-sm text-muted-foreground">正确</div>
              </div>
              <div className="text-center p-4 bg-red-50 dark:bg-red-950 rounded-lg">
                <div className="text-2xl font-bold text-red-600">{SPATIAL_PROBLEMS.length - correctAnswers}</div>
                <div className="text-sm text-muted-foreground">错误</div>
              </div>
              <div className="text-center p-4 bg-blue-50 dark:bg-blue-950 rounded-lg">
                <div className="text-2xl font-bold text-blue-600">{finalResult.score}%</div>
                <div className="text-sm text-muted-foreground">准确率</div>
              </div>
              <div className="text-center p-4 bg-purple-50 dark:bg-purple-950 rounded-lg">
                <div className="text-2xl font-bold text-purple-600">{SPATIAL_PROBLEMS.length}</div>
                <div className="text-sm text-muted-foreground">总题数</div>
              </div>
            </div>

            <div className="space-y-2">
              <h3 className="font-semibold">详细分析</h3>
              <div className="text-sm text-muted-foreground space-y-1">
                <p>• 图形旋转能力: {answers.filter((answer, index) => SPATIAL_PROBLEMS[index]?.type === 'rotation' && answer === SPATIAL_PROBLEMS[index]?.correctAnswer).length}/{SPATIAL_PROBLEMS.filter(p => p.type === 'rotation').length}</p>
                <p>• 心理旋转能力: {answers.filter((answer, index) => SPATIAL_PROBLEMS[index]?.type === 'mental_rotation' && answer === SPATIAL_PROBLEMS[index]?.correctAnswer).length}/{SPATIAL_PROBLEMS.filter(p => p.type === 'mental_rotation').length}</p>
                <p>• 立体折叠理解: {answers.filter((answer, index) => SPATIAL_PROBLEMS[index]?.type === 'folding' && answer === SPATIAL_PROBLEMS[index]?.correctAnswer).length}/{SPATIAL_PROBLEMS.filter(p => p.type === 'folding').length}</p>
                <p>• 透视变换思维: {answers.filter((answer, index) => SPATIAL_PROBLEMS[index]?.type === 'perspective' && answer === SPATIAL_PROBLEMS[index]?.correctAnswer).length}/{SPATIAL_PROBLEMS.filter(p => p.type === 'perspective').length}</p>
                <p>• 截面想象能力: {answers.filter((answer, index) => SPATIAL_PROBLEMS[index]?.type === 'cross_section' && answer === SPATIAL_PROBLEMS[index]?.correctAnswer).length}/{SPATIAL_PROBLEMS.filter(p => p.type === 'cross_section').length}</p>
                {finalResult.score >= 85 && (
                  <p className="text-green-600">• 优秀：空间推理能力很强，具备优秀的3D思维</p>
                )}
                {finalResult.score < 70 && (
                  <p className="text-orange-600">• 建议：加强3D图形观察和空间想象训练</p>
                )}
              </div>
            </div>

            <div className="flex gap-4">
              <Button 
                onClick={() => {
                  setTestCompleted(false);
                  setFinalResult(null);
                  setStarted(false);
                  setCurrentProblem(0);
                  setAnswers([]);
                  setTimeLeft(600);
                  setSelectedAnswer(null);
                  setShowFeedback(false);
                }}
                variant="outline" 
                className="flex-1 border-2 border-slate-300 hover:border-slate-400 hover:bg-slate-50 text-slate-700 hover:text-slate-800 shadow-sm hover:shadow-md transition-all duration-300"
              >
                <RotateCw className="w-4 h-4 mr-2" />
                重新测试
              </Button>
              <Button 
                onClick={handleSaveResult}
                className="flex-1 bg-gradient-to-r from-orange-500 to-amber-600 hover:from-orange-600 hover:to-amber-700 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0"
              >
                <CheckCircle className="w-4 h-4 mr-2" />
                保存结果
              </Button>
            </div>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (currentProblem >= SPATIAL_PROBLEMS.length) {
    return (
      <div className="max-w-2xl mx-auto text-center">
        <motion.div
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          className="space-y-6"
        >
          <div className="w-24 h-24 mx-auto bg-gradient-to-br from-green-400 to-emerald-500 rounded-full flex items-center justify-center">
            <Boxes className="w-12 h-12 text-white" />
          </div>
          <h2 className="text-2xl font-bold">测试完成！</h2>
          <p className="text-muted-foreground">正在分析您的空间推理能力...</p>
        </motion.div>
      </div>
    );
  }

  const problem = SPATIAL_PROBLEMS[currentProblem];
  const progress = ((currentProblem + 1) / SPATIAL_PROBLEMS.length) * 100;
  const timeProgress = (timeLeft / 600) * 100;

  return (
    <motion.div
      initial={{ opacity: 0, scale: 0.95 }}
      animate={{ opacity: 1, scale: 1 }}
      className="max-w-4xl mx-auto space-y-6"
    >
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Badge variant="outline" className="bg-orange-100 text-orange-700 border-orange-300">
            第 {currentProblem + 1} / {SPATIAL_PROBLEMS.length} 题
          </Badge>
          <Badge variant="outline" className={`${
            problem.type === 'rotation' ? 'bg-blue-100 text-blue-700 border-blue-300' :
            problem.type === 'mental_rotation' ? 'bg-purple-100 text-purple-700 border-purple-300' :
            problem.type === 'folding' ? 'bg-green-100 text-green-700 border-green-300' :
            problem.type === 'perspective' ? 'bg-cyan-100 text-cyan-700 border-cyan-300' :
            'bg-pink-100 text-pink-700 border-pink-300'
          }`}>
            {problem.type === 'rotation' ? '图形旋转' :
             problem.type === 'mental_rotation' ? '心理旋转' :
             problem.type === 'folding' ? '立体折叠' :
             problem.type === 'perspective' ? '透视变换' : '截面想象'}
          </Badge>
          <Badge variant="outline" className="bg-slate-100 text-slate-700 border-slate-300">
            难度 {problem.difficulty}/5
          </Badge>
        </div>
        <div className="flex items-center gap-4">
          <Badge variant="secondary" className="flex items-center gap-1">
            ⏰ {formatTime(timeLeft)}
          </Badge>
          <Button
            variant="outline"
            size="sm"
            onClick={skipProblem}
            className="flex items-center gap-1"
          >
            <SkipForward className="w-3 h-3" />
            跳过
          </Button>
        </div>
      </div>

      {/* Progress Bars */}
      <div className="space-y-2">
        <div className="flex justify-between text-sm">
          <span>进度</span>
          <span>{Math.round(progress)}%</span>
        </div>
        <Progress value={progress} className="h-2" />
        
        <div className="flex justify-between text-sm">
          <span>剩余时间</span>
          <span className={timeLeft < 60 ? 'text-red-500' : ''}>
            {formatTime(timeLeft)}
          </span>
        </div>
        <Progress 
          value={timeProgress} 
          className={`h-2 ${timeLeft < 60 ? 'bg-red-100' : ''}`}
        />
      </div>

      {/* Question */}
      <Card className="bg-white/90 backdrop-blur-sm border-orange-200 shadow-lg">
        <CardHeader>
          <CardTitle className="text-lg text-slate-800">
            {problem.question}
          </CardTitle>
          <p className="text-sm text-slate-600">{problem.instruction}</p>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* 主图形显示区域 */}
          <div className="bg-gradient-to-br from-slate-50 to-slate-100 rounded-xl p-8 border-2 border-slate-200">
            <div className="flex justify-center">
              <canvas
                ref={canvasRef}
                width={200}
                height={200}
                className="border border-slate-300 rounded-lg bg-white"
              />
            </div>
          </div>

          {/* Answer Options */}
          <div className="grid grid-cols-2 gap-4">
            <AnimatePresence>
              {[0, 1, 2, 3].map((index) => (
                <motion.div
                  key={index}
                  initial={{ opacity: 0, scale: 0.8 }}
                  animate={{ opacity: 1, scale: 1 }}
                  transition={{ delay: index * 0.1 }}
                >
                  <Button
                    variant={selectedAnswer === index ? 
                      (index === problem.correctAnswer ? "default" : "destructive") : 
                      "outline"
                    }
                    className={`w-full h-32 p-4 transition-all duration-300 ${
                      showFeedback && index === problem.correctAnswer 
                        ? 'bg-green-500 text-white border-green-500 hover:bg-green-600' 
                        : ''
                    }`}
                    onClick={() => handleAnswer(index)}
                    disabled={showFeedback}
                  >
                    <div className="flex flex-col items-center gap-2">
                      <canvas
                        ref={el => optionCanvasRefs.current[index] = el}
                        width={80}
                        height={80}
                        className="border border-slate-200 rounded bg-white"
                      />
                      <span className="font-medium">{String.fromCharCode(65 + index)}</span>
                    </div>
                  </Button>
                </motion.div>
              ))}
            </AnimatePresence>
          </div>

          {/* Feedback */}
          <AnimatePresence>
            {showFeedback && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -20 }}
                className={`text-center p-4 rounded-lg ${
                  selectedAnswer === problem.correctAnswer 
                    ? 'bg-green-50 text-green-700 border border-green-200' 
                    : 'bg-red-50 text-red-700 border border-red-200'
                }`}
              >
                {selectedAnswer === problem.correctAnswer ? (
                  <span>✅ 正确！您的空间想象力很棒！</span>
                ) : (
                  <span>❌ 正确答案是 {String.fromCharCode(65 + problem.correctAnswer)}</span>
                )}
              </motion.div>
            )}
          </AnimatePresence>
        </CardContent>
      </Card>
    </motion.div>
  );
}